﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Compose;
using GalaSoft.MvvmLight;

namespace ConsoleApplication1
{
   public  class Program1: ViewModelBase
    {
        static void Mains(string[] args)
        {
            
           // db= ImportObject<Parts<ICommand, ICommandMedaData>>(".");   //这里的点(.)表示当前应用程序执行目录，从这个目录中查找所有插件。
            //db.Commands.AddRange(res.Commands );
            db = HotRepair<Parts<ICommand, ICommandMedaData>>("."); //这里的点(.)表示当前应用程序执行目录，从这个目录中查找所有插件。
            
            while (true)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("请输入命令和参数：");
                var input = Console.ReadLine();
                Execute(input);
                Console.WriteLine();
            }
        }

        public  static Parts<ICommand, ICommandMedaData> db;

        private static void Execute(string input)
        {
           //db.Commands.Where<Lazy< ICommand, ICommandMedaData> >((x)=>(x.Metadata.CommandName.Equals() ))
           var ps = input.Split(new char[] { ' ' }, 2);
            foreach (var c in db.Commands)
            {
                if (c.Metadata.CommandName.Equals( ps[0],StringComparison.CurrentCultureIgnoreCase ))
                {
                    try
                    {
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine(c.Value.Execute(ps.Length == 2 ? ps[1] : null));
                    }
                    catch (Exception ex)
                    {
                        Console.ForegroundColor = ConsoleColor.Red ;
                        Console.WriteLine(ex.Message);
                    }

                    return;
                }
            }
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("找不到可执行的命令处理程序。");
            Console.ForegroundColor = ConsoleColor.White;
        }


        /// <summary>
        /// 把部件复制到临时文件夹中，从临时文件夹进行加载
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">要复制的目录</param>
        /// <returns></returns>
        public static T HotRepair<T>(string path) where T : new()
        {
            var source = new DirectoryInfo(path);
            var target = new DirectoryInfo(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "compose");
            if (!target.Exists)
                target.Create();
            foreach (var f in source.EnumerateFiles())
            {
                try
                {
                    f.CopyTo(Path.Combine(target.FullName, f.Name),true );
                }
                catch(Exception ex) {
                    string t = ex.Message;
                }
            }
            return ImportObject<T>(target.FullName);
        }


        /// <summary>
        /// 创建T类型对象实例，然后自动填写此对象实例中需要的所有插件（包括插件中间接引用的子插件）。
        /// </summary>
        public static T ImportObject<T>(string dir) where T : new()
        {
            var obj = new T();
               var catalog = new AggregateCatalog();
                catalog.Catalogs.Add(new DirectoryCatalog(dir));
                catalog.Catalogs.Add(new DirectoryCatalog(dir, "*.exe"));
            new CompositionContainer(catalog).ComposeParts(obj);
            
            return obj;
        }


    }
}
